package edu.api.jdbc_api;

import java.sql.*;
import java.util.List;
import java.util.Objects;

/**
 * 为了简化jdbc操作，将重复性 驱动 获取连接 ...封装
 */
public class JDBCUtils {

    //驱动的加载
    static {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    private static final String url = "jdbc:mysql://192.168.220.128:3306/demo?characterEncoding=UTF-8&serverTimezone=Asia/Shanghai";
    private static final String user = "root";
    private static final String password = "123456";

    static Connection connection = null;
    static PreparedStatement statement = null;
    static ResultSet resultSet = null;


    /**
     * 数据库连接的获取
     *
     * @return
     * @throws SQLException
     */
    public static Connection getConnection() throws SQLException {
        connection = DriverManager.getConnection(url, user, password);
        return connection;
    }

    /**
     * 增删改
     *
     * @param sql    sql语句
     * @param params sql中需要传递的参数
     */
    public static int update(String sql, List<Object> params) throws SQLException {
        connection = getConnection();
        statement = connection.prepareStatement(sql);
        //sql的预处理参数
        if (!(Objects.isNull(params) || params.size() == 0)) {
            for (int i = 0; i < params.size(); i++) {
                statement.setObject(i + 1, params.get(i));
            }
        }
        int i = statement.executeUpdate();
        return i;
    }


    /**
     * 查询
     * @param sql sql语句
     * @param params sql中的参数集合
     */
    public static ResultSet query(String sql,List<Object> params) throws SQLException {
        connection = getConnection();
        statement = connection.prepareStatement(sql);
        //sql的预处理参数
        if (!(Objects.isNull(params) || params.size() == 0)) {
            for (int i = 0; i < params.size(); i++) {
                statement.setObject(i + 1, params.get(i));
            }
        }
        ResultSet resultSet = statement.executeQuery();
        return resultSet;
    }

    public static void close() throws SQLException {
        if (statement != null){
            statement.close();
        }
        if (connection != null){
            connection.close();
        }
    }


}
